
 <!DOCTYPE HTML>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="baidu-site-verification" content="g6aOnZn9cI" />
  
    <title>handler post remove | hello,world!</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
    
    <meta name="author" content="小强">
    

    
    <meta name="description" content="Handler post描述在Handler使用中，可以通过各种方法把一个Message添加到MessageQueue中。
方法列表123456789101112131415161. post(Runnable r)2. postAtFrontOfQueue(Runnable r)3. postAtTime(Runnable r, long uptimeMillis)4. postAtTime(R">
<meta property="og:type" content="article">
<meta property="og:title" content="handler post remove">
<meta property="og:url" content="https://wang12.github.io/2016/12/17/handler-post-remove/index.html">
<meta property="og:site_name" content="hello,world!">
<meta property="og:description" content="Handler post描述在Handler使用中，可以通过各种方法把一个Message添加到MessageQueue中。
方法列表123456789101112131415161. post(Runnable r)2. postAtFrontOfQueue(Runnable r)3. postAtTime(Runnable r, long uptimeMillis)4. postAtTime(R">
<meta property="og:updated_time" content="2016-12-26T03:32:01.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="handler post remove">
<meta name="twitter:description" content="Handler post描述在Handler使用中，可以通过各种方法把一个Message添加到MessageQueue中。
方法列表123456789101112131415161. post(Runnable r)2. postAtFrontOfQueue(Runnable r)3. postAtTime(Runnable r, long uptimeMillis)4. postAtTime(R">

    
    <link rel="alternative" href="/atom.xml" title="hello,world!" type="application/atom+xml">
    
    
    <link rel="icon" href="/img/logo.png">
    
    
    <link rel="apple-touch-icon" href="/img/jacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/img/jacman.jpg">
    
    <link rel="stylesheet" href="/css/style.css">
</head>

  <body>
    <header>
      <meta name="baidu-site-verification" content="g6aOnZn9cI" />
      
<div>
		
			<div id="imglogo">
				<a href="/"><img src="/img/logo.png" alt="hello,world!" title="hello,world!"/></a>
			</div>
			
			<div id="textlogo">
				<h1 class="site-name"><a href="/" title="hello,world!">hello,world!</a></h1>
				<h2 class="blog-motto">告诉自己，你还需要更加努力!!</h2>
			</div>
			<div class="navbar"><a class="navbutton navmobile" href="#" title="菜单">
			</a></div>
			<nav class="animated">
				<ul>
					<ul>
					 
						<li><a href="/">首页</a></li>
					
						<li><a href="/archives">归档</a></li>
					
						<li><a href="/about">关于</a></li>
					
					<li>
 					
						<form class="search" action="https://www.baidu.com/" target="_blank">
							<label>Search</label>
						<input name="s" type="hidden" value= null ><input type="text" name="q" size="30" placeholder="搜索"><br>
						</form>
					
					</li>
				</ul>
			</nav>
</div>

    </header>
    <div id="container">
      <div id="main" class="post" itemscope itemprop="blogPost">
  
	<article itemprop="articleBody"> 
		<header class="article-info clearfix">
  <meta name="baidu-site-verification" content="g6aOnZn9cI" />
  <h1 itemprop="name">
    
      <a href="/2016/12/17/handler-post-remove/" title="handler post remove" itemprop="url">handler post remove</a>
  </h1>
  <p class="article-author">By
       
		<a href="/about" title="小强" target="_blank" itemprop="author">小强</a>
		
  <p class="article-time">
    <time datetime="2016-12-17T10:53:32.000Z" itemprop="datePublished"> 发表于 2016-12-17</time>

  </p>
</header>

	<div class="article-content">
		
		<div id="toc" class="toc-article">
			<strong class="toc-title">文章目录</strong>
		
			<ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Handler-post"><span class="toc-number">1.</span> <span class="toc-text">Handler post</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#描述"><span class="toc-number">1.1.</span> <span class="toc-text">描述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#方法列表"><span class="toc-number">1.2.</span> <span class="toc-text">方法列表</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Handler-remove"><span class="toc-number">2.</span> <span class="toc-text">Handler remove</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#描述-1"><span class="toc-number">2.1.</span> <span class="toc-text">描述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#方法列表-1"><span class="toc-number">2.2.</span> <span class="toc-text">方法列表</span></a></li></ol></li></ol>
		
		</div>
		
		<h1 id="Handler-post"><a href="#Handler-post" class="headerlink" title="Handler post"></a>Handler post</h1><h2 id="描述"><a href="#描述" class="headerlink" title="描述"></a>描述</h2><pre><code>在Handler使用中，可以通过各种方法把一个Message添加到MessageQueue中。
</code></pre><h2 id="方法列表"><a href="#方法列表" class="headerlink" title="方法列表"></a>方法列表</h2><pre><code><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="number">1</span>. post(Runnable r)</div><div class="line"><span class="number">2</span>. postAtFrontOfQueue(Runnable r)</div><div class="line"><span class="number">3</span>. postAtTime(Runnable r, <span class="keyword">long</span> uptimeMillis)</div><div class="line"><span class="number">4</span>. postAtTime(Runnable r, Object token, <span class="keyword">long</span> uptimeMillis)</div><div class="line"><span class="number">5</span>. postDelayed(Runnable r, <span class="keyword">long</span> delayMillis)</div><div class="line"></div><div class="line"><span class="number">6</span>. sendEmptyMessage(<span class="keyword">int</span> what)</div><div class="line"><span class="number">7</span>. sendEmptyMessageAtTime(<span class="keyword">int</span> what, <span class="keyword">long</span> uptimeMillis)</div><div class="line"><span class="number">8</span>. 	sendEmptyMessageDelayed(<span class="keyword">int</span> what, <span class="keyword">long</span> delayMillis)</div><div class="line"><span class="number">9</span>. sendMessage(Message msg)</div><div class="line"><span class="number">10</span>. sendMessageAtFrontOfQueue(Message msg)</div><div class="line"><span class="number">11</span>. sendMessageAtTime(Message msg, <span class="keyword">long</span> uptimeMillis)</div><div class="line"><span class="number">12</span>. sendMessageDelayed(Message msg, <span class="keyword">long</span> delayMillis)</div><div class="line"></div><div class="line"><span class="comment">//Message </span></div><div class="line"><span class="number">13</span>. sendToTarget()</div></pre></td></tr></table></figure>
</code></pre><p>内部方法调用</p>
<pre><code>1  -&gt; 12 -&gt; 11
2  -&gt; 10
3  -&gt; 11
4  -&gt; 11
5  -&gt; 12 -&gt; 11
6  -&gt; 8  -&gt; 12 -&gt; 11
7  -&gt; 11
9  -&gt; 12 -&gt; 11
</code></pre><p>可以看到，方法最终调用到 11和10 这两个方法。其他的参数都是为了向Message中添加元素。</p>
<p>sendMessageAtFrontOfQueue(Message msg)<br>//把这个Message放到最前面。也就是下一个就会立即执行Message </p>
<ul>
<li><font color="red">This method is only for use in very special circumstances – it can easily starve the message queue, cause ordering problems, or have other unexpected side-effects.</font>

<p>大概意思是这个方法用在一些特殊的情况下。不过可能会导致消息队列锁死或者导致消息排序问题。总结下来就一句话，别用这个方法</p>
</li>
</ul>
<p>sendMessageAtTime(Message msg, long uptimeMillis)<br>//在一个确定的时间执行Message</p>
<ul>
<li><font color="blue">注意，这里的时间是手机启动至今运行的时间，并不是其他的绝对时间。所有使用时一定要注意，如果你发现使用这个方法，但是立即执行了Message或者过了好久好久也不执行。那也就理所当然了。</font></li>
<li><font color="red">如果你对这里的uptimeMillil设置为0，其实和sendMessageAtFrontOfQueue 执行一样。这里应该也是不安全的</font>

</li>
</ul>
<p>sendEmptyMessageDelayed</p>
<p> //这个方法其实还是调用了sendMessageAtTime 方法。只不过唯一的区别是使用delayed自己计算了绝对时间。计算方式就是”SystemClock.uptimeMillis() + delayMillis”。</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//返回一个毫秒值，表示系统自启动以来的时间，不包括深度睡眠时间</span></div><div class="line">SystemClock.uptimeMillis()</div></pre></td></tr></table></figure>
<hr>
<h1 id="Handler-remove"><a href="#Handler-remove" class="headerlink" title="Handler remove"></a>Handler remove</h1><h2 id="描述-1"><a href="#描述-1" class="headerlink" title="描述"></a>描述</h2><p>移除消息是很重要的。比如你通过postDelay做一个定时器，然后定时器在OnResume中启动。但是你在onStop中不退出会如何。<br>答案就是你在后台回来的时候，发现定时器完全乱了。。</p>
<h2 id="方法列表-1"><a href="#方法列表-1" class="headerlink" title="方法列表"></a>方法列表</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">removeCallbacks(Runnable r)</div><div class="line">		--&gt; mQueue.removeMessages(<span class="keyword">this</span>, r, <span class="keyword">null</span>);</div><div class="line">removeCallbacks(Runnable r, Object token)</div><div class="line">		--&gt; mQueue.removeMessages(<span class="keyword">this</span>, r, token);</div><div class="line">removeMessages(<span class="keyword">int</span> what)</div><div class="line">		--&gt; mQueue.removeMessages(<span class="keyword">this</span>, what, <span class="keyword">null</span>);</div><div class="line">removeMessages(<span class="keyword">int</span> what, Object object)</div><div class="line">		--&gt; mQueue.removeMessages(<span class="keyword">this</span>, what, object);</div><div class="line">removeCallbacksAndMessages(Object token)</div><div class="line">		--&gt; mQueue.removeCallbacksAndMessages(<span class="keyword">this</span>, token);</div></pre></td></tr></table></figure>
<p>removeIdleHandler(IdleHandler handler) ???? </p>
<p>可以看到，所有的移除方法都是调用了消息队列中的移除。一共分为三类，根据Runnable移除、根据 what和object 移除以及根据token移除</p>
<ul>
<li><p>removeMessages(Handler h, Runnable r, Object object)</p>
<ol>
<li>首先保证handler和Runnable 都不为空</li>
<li>接下来判断当前正要处理的Message是不是你要移除的，如果是，那么指向下一个Message，并且回收当前Message</li>
<li>接下来循环处理所有Message消息，如果handler,runnable,和Message.obj和传入的一样，那么全部回收掉message </li>
<li>所谓的从消息队列中移除，只不过是把前一个Message的指针指向下下一个Message。这样就丢掉了符合条件的Message</li>
</ol>
</li>
<li><p>removeMessages(Handler h, int what, Object object)</p>
<p>  这个方法的是实现方式和第一个完全一样，只是更换了判断标准</p>
</li>
<li><p>removeCallbacksAndMessages(Handler h, Object object)</p>
<p>  如果object为空，那么可以移除当前Handler中的所有Message消息。直接使用post(Runnable),实际上还是封装成一个Message消息。</p>
</li>
</ul>
<hr>
<p>在看MessageQueue的时候，突然间发现两个没有使用过的方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">Looper.myQueue().addIdleHandler();</div><div class="line">Looper.myQueue().removeIdleHandler();</div></pre></td></tr></table></figure>
<p>通过各种网络资源，说是添加的IdleHandler是在MessageQueue线程中没有Message消息，或者说空闲时间会使用。</p>
<p>最常规的用法，在Actviity中添加这个。<br>当Activity显示出来的时候就会回调。如果返回false。那么只会回调一次。</p>
<p>我测试发现，一般是在onResume之后回调。</p>
  
	</div>
		<footer class="article-footer clearfix">
<div class="article-catetags">

<div class="article-categories">
  <span></span>
  <a class="article-category-link" href="/categories/android/">android</a>
</div>


  <div class="article-tags">
  
  <span></span> <a href="/tags/source/">source</a>
  </div>

</div>



	<div class="article-share" id="share">
	
	<div class="share-jiathis">
	  
<div class="jiathis_style_24x24">
	<a class="jiathis_button_tsina"></a>
	<a class="jiathis_button_weixin"></a>
	<a class="jiathis_button_renren"></a>
	<a class="jiathis_button_qzone"></a>
	<a class="jiathis_button_googleplus"></a>
	<a class="jiathis_button_douban"></a>
	<a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jtico jtico_jiathis" target="_blank"></a>
	<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
    var jiathis_config={
    data_track_clickback:true,
    sm:"copy,renren,cqq",
    pic:"",
    summary:"",
    
  </script> 
<script type="text/javascript" src="//v3.jiathis.com/code/jia.js?uid=
" charset="utf-8"></script>      

	 </div>
	
	</div>


</footer>

   	       
	</article>
	
<nav class="article-nav clearfix">
 
 <div class="prev" >
 <a href="/2017/02/08/View滑动/" title="View 滑动效果">
  <strong>上一篇：</strong><br/>
  <span>
  View 滑动效果</span>
</a>
</div>


<div class="next">
<a href="/2016/11/29/Message-Looper-and-MessageQueue-创建2/"  title="Looper and MessageQueue创建">
 <strong>下一篇：</strong><br/> 
 <span>Looper and MessageQueue创建
</span>
</a>
</div>

</nav>

	

</div>  
      <div class="openaside"><a class="navbutton" href="#" title="显示侧边栏"></a></div>

  <div id="toc" class="toc-aside">
  <strong class="toc-title">文章目录</strong>
 
 <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Handler-post"><span class="toc-number">1.</span> <span class="toc-text">Handler post</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#描述"><span class="toc-number">1.1.</span> <span class="toc-text">描述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#方法列表"><span class="toc-number">1.2.</span> <span class="toc-text">方法列表</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Handler-remove"><span class="toc-number">2.</span> <span class="toc-text">Handler remove</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#描述-1"><span class="toc-number">2.1.</span> <span class="toc-text">描述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#方法列表-1"><span class="toc-number">2.2.</span> <span class="toc-text">方法列表</span></a></li></ol></li></ol>
 
  </div>

<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="隐藏侧边栏"></a></div>
<aside class="clearfix">

  
<div class="categorieslist">
	<p class="asidetitle">分类</p>
		<ul>
		
		  
			<li><a href="/categories/android/" title="android">android<sup>19</sup></a></li>
		  
		
		  
			<li><a href="/categories/other/" title="other">other<sup>1</sup></a></li>
		  
		
		</ul>
</div>


  
<div class="tagslist">
	<p class="asidetitle">标签</p>
		<ul class="clearfix">
		
			
				<li><a href="/tags/学习/" title="学习">学习<sup>7</sup></a></li>
			
		
			
				<li><a href="/tags/bug/" title="bug">bug<sup>5</sup></a></li>
			
		
			
				<li><a href="/tags/source/" title="source">source<sup>4</sup></a></li>
			
		
			
				<li><a href="/tags/function/" title="function">function<sup>3</sup></a></li>
			
		
		</ul>
</div>


  <div class="linkslist">
  <p class="asidetitle">友情链接</p>
    <ul>
        
          <li>
            
            	<a href="http://blog.csdn.net/" target="_blank" title="CSDN社区">CSDN 社区</a>
            
          </li>
        
          <li>
            
            	<a href="https://developer.android.com/index.html" target="_blank" title="android developer">android developer</a>
            
          </li>
        
          <li>
            
            	<a href="https://developers.google.com/vr/" target="_blank" title="google vr">google vr</a>
            
          </li>
        
    </ul>
</div>

  <div class="weiboshow">
  <p class="asidetitle">新浪微博</p>
    <iframe width="100%" height="119" class="share_self"  frameborder="0" scrolling="no" src="http://widget.weibo.com/weiboshow/index.php?language=&width=0&height=119&fansRow=2&ptype=1&speed=0&skin=9&isTitle=1&noborder=1&isWeibo=0&isFans=0&uid=null&verifier=3a89c19b&dpc=1"></iframe>
</div>


</aside>
</div>
    </div>
    <footer><div id="footer" >
	
	<div class="line">
		<span></span>
		<div class="author"></div>
	</div>
	
	
	<section class="info">
		<p>  IT小强,希望每天都开心 <br/>
			写给自己的博客</p>
	</section>
	 
	<div class="social-font" class="clearfix">
		
		<a href="http://weibo.com/3535012745" target="_blank" class="icon-weibo" title="微博"></a>
		
		
		<a href="https://github.com/827498077@qq.com" target="_blank" class="icon-github" title="github"></a>
		
		
		
		
		
		
		
		
		
		<a href="mailto:827498077@qq.com" target="_blank" class="icon-email" title="Email Me"></a>
		
	</div>
			
		

		<p class="copyright">
	 	 博客创建日期 @ 2016.11.05 19:00
		</p>
</div>
</footer>
    <script src="/js/jquery-2.0.3.min.js"></script>
<script src="/js/jquery.imagesloaded.min.js"></script>
<script src="/js/gallery.js"></script>
<script src="/js/jquery.qrcode-0.12.0.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){ 
  $('.navbar').click(function(){
    $('header nav').toggleClass('shownav');
  });
  var myWidth = 0;
  function getSize(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
  };
  var m = $('#main'),
      a = $('#asidepart'),
      c = $('.closeaside'),
      o = $('.openaside');
  c.click(function(){
    a.addClass('fadeOut').css('display', 'none');
    o.css('display', 'block').addClass('fadeIn');
    m.addClass('moveMain');
  });
  o.click(function(){
    o.css('display', 'none').removeClass('beforeFadeIn');
    a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');      
    m.removeClass('moveMain');
  });
  $(window).scroll(function(){
    o.css("top",Math.max(80,260-$(this).scrollTop()));
  });
  
  $(window).resize(function(){
    getSize(); 
    if (myWidth >= 1024) {
      $('header nav').removeClass('shownav');
    }else{
      m.removeClass('moveMain');
      a.css('display', 'block').removeClass('fadeOut');
      o.css('display', 'none');
      
      $('#toc.toc-aside').css('display', 'none');
        
    }
  });
});
</script>

<script type="text/javascript">
$(document).ready(function(){ 
  var ai = $('.article-content>iframe'),
      ae = $('.article-content>embed'),
      t  = $('#toc'),
      ta = $('#toc.toc-aside'),
      o  = $('.openaside'),
      c  = $('.closeaside');
  if(ai.length>0){
    ai.wrap('<div class="video-container" />');
  };
  if(ae.length>0){
   ae.wrap('<div class="video-container" />');
  };
  c.click(function(){
    ta.css('display', 'block').addClass('fadeIn');
  });
  o.click(function(){
    ta.css('display', 'none');
  });
  $(window).scroll(function(){
    ta.css("top",Math.max(140,320-$(this).scrollTop()));
  });
});
</script>










<link rel="stylesheet" href="/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.article-content').each(function(i){
    $(this).find('img').each(function(){
      if ($(this).parent().hasClass('fancybox')) return;
      var alt = this.alt;
      if (alt) $(this).after('<span class="caption">' + alt + '</span>');
      $(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
    });
    $(this).find('.fancybox').each(function(){
      $(this).attr('rel', 'article' + i);
    });
  });
  if($.fancybox){
    $('.fancybox').fancybox();
  }
}); 
</script>



<!-- Analytics Begin -->



<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?26cff7ff569b956a445199e85c2a0e30";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>



<!-- Analytics End -->

<!-- Totop Begin -->

	<div id="totop">
	<a title="返回顶部"><img src="/img/scrollup.png"/></a>
	</div>
	<script src="/js/totop.js"></script>

<!-- Totop End -->

<!-- MathJax Begin -->
<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true
    }
  });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


<!-- MathJax End -->

<!-- Tiny_search Begin -->

<!-- Tiny_search End -->

  </body>
</html>

